//
//  UserZoneViewController.m
//  JxCarios
//
//  Created by xcq on 15/1/21.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "UserZoneViewController.h"
#import "Common.h"
@interface UserZoneViewController () <UIActionSheetDelegate,UIAlertViewDelegate>
{
    BOOL bol;
}
@end

@implementation UserZoneViewController

- (void)viewWillAppear:(BOOL)animated{
    //TODO:判断是否登陆
    if([Common currenLoginStatus]){
        [self getUserData];
        [_loginBtn setTitle:@"退出" forState:UIControlStateNormal];
    }else {
        _userName.text = @"0";
        _userScore.text = @"积分:";
        _userPhoto.image = [UIImage imageNamed:@"11"];
        bol = NO;
        [_loginBtn setTitle:@"登陆" forState:UIControlStateNormal];

    }
}

-(void)networkingStartHandleWithRequestIdentifier:(RequestIdentifier)identifier {
    
}

-(void)networkingCompleteHandleWithRequestIdentifier:(RequestIdentifier)identifier {
    
}

-(void)networkingFailureHandleWithRequestIdentifier:(RequestIdentifier)identifier errorMessage:(NSString *)message {
    [super networkingFailureHandleWithRequestIdentifier:identifier errorMessage:message];
}

- (void)getUserData {
    if (!self.dataSource) {
        self.dataSource = [CurrentDataSource dataSourceWithRequestor:self];
    }
    [self.dataSource getUserInfo:^(id result) {
        [Common setUserInfo:[result customObjectForkey:@"memberinfo"]];
        if (bol) {
            
        }else{
        [_userPhoto setImageWithURL:[NSURL URLWithString:[[result customObjectForkey:@"memberinfo"] customObjectForkey:@"HEAD_PIC"]] placeholderImage:[UIImage imageNamed:@"11"]];
        }
        _userName.text = [Common currentUserName];
        _userScore.text = [@"积分:" stringByAppendingString:[NSString stringWithFormat:@"%@",[Common currenVB]]];
    } andFail:^(id result) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    bol = NO;
    [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    _loginBtn.backgroundColor = BTN_COLOR;
}


- (void)pushToLogin {
    LoginViewController *login = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginView"];
    CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:login];
    login.hidesBottomBarWhenPushed = YES;
    [self presentViewController:base animated:YES completion:nil];
}

- (IBAction)imageTapAction:(UIButton *)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"手机相册", nil];
    [sheet showInView:self.view.window];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIImagePickerControllerSourceType sourceType;
    if (buttonIndex == 0) { //照相机
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"相机不可用,请到设置中打开相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentImagePicker:sourceType];
        }
    }else if (buttonIndex == 1) { //手机相册
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentImagePicker:sourceType];
    }else if (buttonIndex == 2){
        
    }
}

- (void)presentImagePicker:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
}


//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    // 保存图片至本地，方法见下文
     _userPhoto.image = image;
     bol = YES;
     [self uploadUserPhoto:image];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (NSString *)returnPhoneFilePath:(BOOL)isExists{
#warning 修改照片存放路径
    NSString *fileName = [[NSString stringWithFormat:@"%@_%@", [Common currentUserName], [Common currentUserId]] stringByAppendingPathExtension:@"jpg"];
    NSString *filePath = [DocumentsDirectory stringByAppendingPathComponent:fileName];
    if(isExists){
        [FileIO removeItemAtPath:filePath];
    }
    return filePath;
}

- (void)loginAction:(id)sender {
    
    if ([_loginBtn.titleLabel.text isEqualToString:@"退出"]) {
         [Common showLocalAlert:@"提示" message:@"您确定要退出吗?" delegate:self andTag:1034];
       
     }else{
        [self pushToLogin];
    }
}


#pragma mark - alertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1001) {
        if (buttonIndex == 0) {
            [self.tabBarController setSelectedIndex:0];
        }else{
            [self pushToLogin];
        }
    }else if (alertView.tag == 1034){
        if (buttonIndex == 1) {
            [Common setLoginStatus:NO];
            [_loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
            _userName.text = @"0";
            _userScore.text = @"积分:";
            _userPhoto.image = [UIImage imageNamed:@"11"];
            bol = NO;
        }
        
    }
}



#pragma mark - 设置头像

#pragma mark - 上传头像
- (void)uploadUserPhoto:(UIImage*)image {
    //TODO:上传图片
    [Common upLoadImage:@"http://tapi.clejw.com/upheadimg.jsp" andFileSuffixRandom:10000 andFile:image andSucces:^(id result) {
        NSLog(@"success");
        
    } andFail:^(id result) {
        NSError *error = (NSError *)result;
        NSLog(@"%@",error.localizedDescription);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)czAction:(id)sender {
}



- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([identifier isEqualToString:@"pushShare"] || [identifier isEqualToString:@"pushAbout"]) {
        return YES;
    }
    if (![Common currenLoginStatus]) {
        [self pushToLogin];
        return NO;
        
    }
    
    return YES;
    
}

@end
